package com.ruoyi.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.conf.MinioConfig;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;


/**
 * 用户分配号码Controller
 * 
 * @author xyz
 * @date 2025-05-14
 */
@RestController
@RequestMapping("/system/info")
public class UserInfoController extends BaseController
{
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 查询用户分配号码列表
     */
//    @PreAuthorize("@ss.hasPermi('system:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserInfo userInfo)
    {
        startPage();
        List<UserInfo> list = userInfoService.selectUserInfoList(userInfo);
        return getDataTable(list);
    }

    /**
     * 导出用户分配号码列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "用户分配号码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserInfo userInfo)
    {
        List<UserInfo> list = userInfoService.selectUserInfoList(userInfo);
        ExcelUtil<UserInfo> util = new ExcelUtil<UserInfo>(UserInfo.class);
        util.exportExcel(response, list, "用户分配号码数据");
    }

    /**
     * 获取用户分配号码详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userInfoService.selectUserInfoById(id));
    }

    /**
     * 生成二维码
     */
    @PostMapping("/generate")
    public AjaxResult generateQrCode(@RequestBody Map<String, String> body) {
        String content = body.get("content");
        if (content == null || content.isEmpty()) {
            return AjaxResult.error("二维码内容不能为空");
        }

        try {
            // 生成二维码图片到内存
            int width = 200;
            int height = 200;
            String format = "png";
            Map<com.google.zxing.EncodeHintType, Object> hints = new java.util.HashMap<>();
            hints.put(com.google.zxing.EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(com.google.zxing.EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H);
            hints.put(com.google.zxing.EncodeHintType.MARGIN, 1);

            com.google.zxing.common.BitMatrix bitMatrix = new com.google.zxing.MultiFormatWriter().encode(
                    content, com.google.zxing.BarcodeFormat.QR_CODE, width, height, hints);

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            com.google.zxing.client.j2se.MatrixToImageWriter.writeToStream(bitMatrix, format, os);
            byte[] imageBytes = os.toByteArray();

            // 上传到MinIO
            String fileName = "qrcode-" + System.currentTimeMillis() + ".png";
            InputStream inputStream = new ByteArrayInputStream(imageBytes);
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .stream(inputStream, imageBytes.length, -1)
                            .contentType("image/png")
                            .build()
            );

            // 构建访问URL
            String url = minioConfig.getPublicUrl(fileName);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error("生成二维码失败: " + e.getMessage());
        }
    }

    /**
     * 获取请求的根URL
     */
    private String getUrl(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }


    /**
     * 新增用户分配号码
     */
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "用户分配号码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserInfo userInfo)
    {
        return toAjax(userInfoService.insertUserInfo(userInfo));
    }

    /**
     * 修改用户分配号码
     */
    @PreAuthorize("@ss.hasPermi('system:info:edit')")
    @Log(title = "用户分配号码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserInfo userInfo)
    {
        return toAjax(userInfoService.updateUserInfo(userInfo));
    }

    /**
     * 删除用户分配号码
     */
    @PreAuthorize("@ss.hasPermi('system:info:remove')")
    @Log(title = "用户分配号码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userInfoService.deleteUserInfoByIds(ids));
    }


    /**
     * 分配号码并新增一条记录
     */
//    @PreAuthorize("@ss.hasPermi('system:info:add')")
//    @Log(title = "用户分配号码", businessType = BusinessType.INSERT)
    @PostMapping("/assign")
    public AjaxResult assign(@RequestBody SysUser user)
    {
        return userInfoService.assignNumber(user);
    }
    
    /**
     * 重置所有用户的number字段为空
     */
    @PostMapping("/resetAllUserNumber")
    public AjaxResult resetAllUserNumber() {
        int rows = userInfoService.resetAllUserNumber();
        return AjaxResult.success("已重置所有用户的number字段为空", rows);
    }

// 在这里实现生成二维码

}
